package com.yupi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.model.dto.question.QuestionAddRequest;
import com.yupi.project.model.dto.question.QuestionQueryRequest;
import com.yupi.project.model.dto.question.QuestionUpdateRequest;
import com.yupi.project.model.entity.Product;
import com.yupi.project.model.entity.Question;
import com.yupi.project.model.entity.Resourse;
import com.yupi.project.model.vo.QuestionVo;
import com.yupi.project.service.ProductService;
import com.yupi.project.service.QuestionService;
import com.yupi.project.service.ResourseService;
import com.yupi.project.util.FileUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("question")
@CrossOrigin
public class QuestionController {


    @Resource
    private QuestionService questionService;


    @Resource
    private FileUtil fileUtil;

    @Resource
    private ResourseService resourseService;

    @Resource
    private ProductService productService;

    /**
     * 增加产品
     *
     * @return
     */
    @PostMapping("")
    public BaseResponse<Long> addQuestion(QuestionAddRequest questionAddRequest) {

        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!StringUtils.isNotBlank(questionAddRequest.getProblem())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "问题不能为空");
        }

        if (!StringUtils.isNotBlank(questionAddRequest.getAnswer())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "问题不能为空");
        }

        if (questionAddRequest.getProductid() == null || questionAddRequest.getProductid() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请绑定所属问题");
        }


//
        Long id = questionService.saveQuestion(questionAddRequest);

        return ResultUtils.success(id);


    }

    /**
     * 修改产品
     *
     * @return
     */
    @PutMapping("")
    public BaseResponse<Long> updateQuestion(QuestionUpdateRequest questionUpdateRequest) {

        if (questionUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (questionUpdateRequest.getId() == 0 || questionUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该产品不存在");
        }


//
        Long id = questionService.updateQuestion(questionUpdateRequest);

        return ResultUtils.success(id);

    }


    /**
     * 删除产品
     *
     * @return
     */
    @DeleteMapping("")
    public BaseResponse<Boolean> deleteQuestion(Long id) {

        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该产品不存在");
        }

//
        Boolean b = questionService.deleteQuestion(id);
        return ResultUtils.success(b);

    }

    @GetMapping("single")
    public BaseResponse<QuestionVo> getQuestionById(Long id) {
        Question byId = questionService.getById(id);

        if (byId != null) {
            LambdaQueryWrapper<Resourse> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Resourse::getQuestionid, byId.getId()).eq(Resourse::getStatu, 1);
            List<Resourse> list = resourseService.list(queryWrapper);
            String preurl = fileUtil.getPreurl();
            List<String> collect = list.stream().map(resourse -> preurl + resourse.getUrl()).collect(Collectors.toList());
            QuestionVo questionVo = new QuestionVo();
            BeanUtils.copyProperties(byId, questionVo);
            questionVo.setQuestionUrlList(collect);

            LambdaQueryWrapper<Resourse> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Resourse::getQuestionid, byId.getId()).eq(Resourse::getStatu, 2);
            List<Resourse> list1 = resourseService.list(queryWrapper1);
//        String preurl = fileUtil.getPreurl();
            List<String> collect1 = list1.stream().map(resourse -> preurl + resourse.getUrl()).collect(Collectors.toList());
            questionVo.setAnswerUrlList(collect1);

            return ResultUtils.success(questionVo);
        }

        throw new BusinessException(ErrorCode.PARAMS_ERROR, "该问题不存在");

    }


    /**
     * 根据类别id、产品名称查询
     */
    @GetMapping()
    public BaseResponse<Page<QuestionVo>> getQuestion(QuestionQueryRequest questionQueryRequest) {

        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(questionQueryRequest.getProductname())) {
//           先查出商品id
            LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
            productLambdaQueryWrapper.like(Product::getName, questionQueryRequest.getProductname());
            List<Product> list = productService.list(productLambdaQueryWrapper);
            if (list != null && list.size() != 0) {
                List<Long> collect = list.stream().map(Product::getId).collect(Collectors.toList());
                queryWrapper.in(Question::getProductid, collect);
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "该商品不存在");
            }

        }

        if (questionQueryRequest.getProductid()!=null && questionQueryRequest.getProductid()!=0){
            queryWrapper.eq(Question::getProductid,questionQueryRequest.getProductid() );
        }


        if (StringUtils.isNotBlank(questionQueryRequest.getProblem())) {
            queryWrapper.like(Question::getProblem, questionQueryRequest.getProblem());
        }

        Page<Question> page = questionService.page(new Page<>(questionQueryRequest.getCurrent(),
                questionQueryRequest.getPageSize()), queryWrapper);

//        将Question转为QuestionVof
        Page<QuestionVo> questionVoPage = new Page<>();
        BeanUtils.copyProperties(page, questionVoPage);


        List<QuestionVo> questionVoList = page.getRecords().stream().map(question -> {
            QuestionVo questionVo = new QuestionVo();
            BeanUtils.copyProperties(question, questionVo);
            return questionVo;
        }).collect(Collectors.toList());

//        检索出所有的图片
        String preurl = fileUtil.getPreurl();
        LambdaQueryWrapper<Resourse> resourseLambdaQueryWrapper = new LambdaQueryWrapper<>();

        questionVoList.forEach(questionVo -> {
            LambdaQueryWrapper<Resourse> questionquerywapper = new LambdaQueryWrapper<>();
            questionquerywapper.eq(Resourse::getQuestionid, questionVo.getId()).eq(Resourse::getStatu, 1);
            List<Resourse> list = resourseService.list(questionquerywapper);

            if (list != null && list.size() != 0) {
                questionVo.setQuestionUrlList(
                        list.stream().map(resourse -> preurl + resourse.getUrl()).collect(Collectors.toList()));
            }

//            回答的
            LambdaQueryWrapper<Resourse> answer = new LambdaQueryWrapper<>();
            answer.eq(Resourse::getQuestionid, questionVo.getId()).eq(Resourse::getStatu, 2);
            List<Resourse> answerlist = resourseService.list(answer);

            if (answerlist != null && answerlist.size() != 0) {
                questionVo.setAnswerUrlList(
                        answerlist.stream().map(resourse -> preurl + resourse.getUrl()).collect(Collectors.toList()));
            }

        });
        questionVoPage.setRecords(questionVoList);

        return ResultUtils.success(questionVoPage);
    }

    @PostMapping("resource")
    public void deleteResourse(String url) {
        String preurl = fileUtil.getPreurl();
        String replace = url.replace(preurl, "");

        LambdaQueryWrapper<Resourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Resourse::getUrl, replace);
        Resourse one = resourseService.getOne(queryWrapper);
        if (one != null) {
            resourseService.remove(queryWrapper);
            fileUtil.removeFile(one.getUrl());
        }
    }

}

@Data
@EqualsAndHashCode
class GroupKey {
    public GroupKey(Long questionid, Integer statu) {
        this.questionid = questionid;
        this.statu = statu;
    }

    /**
     * 问题id
     */
    private Long questionid;

    /**
     * 1——问题的图片；2——回答的图片
     */
    private Integer statu;
}
